<template>
  <div id="userLoginPage">
    <van-nav-bar left-text="返回" left-arrow @click-left="router.back()" />
    <h2 style="text-align: center; margin-bottom: 32px;">用户登录</h2>
    <van-form @submit="handleSubmit">
      <van-cell-group inset>
        <van-field v-model="form.userAccount" name="用户名" label="用户名" placeholder="用户名" :rules="[{ required: true, message: '请填写用户名' }]" />
        <van-field v-model="form.userPassword" type="password" name="密码" label="密码" placeholder="密码" :rules="[{ required: true, message: '请填写密码' }]" />
      </van-cell-group>
      <div style="margin: 16px;">
        <van-button round block type="primary" native-type="submit"  style="max-width: 300px; margin: 0 auto;"> 登录 </van-button>
        <div style="margin-top: 8px; display: flex; width: 100%; align-items: center; justify-content: space-between;">
          <div>其他登录方式：<van-button @click="wxLogin">微信登录</van-button></div>
          <p>没有账号？<router-link to="/auth/register">点击注册</router-link></p>
        </div>
      </div>
    </van-form>
  </div>
</template>

<script setup lang="ts">
import { reactive, computed } from "vue";
import API from "@/api";
import { showSuccessToast, showFailToast, showLoadingToast, closeToast } from 'vant';
import { useRouter, useRoute } from "vue-router";

const router = useRouter();
const route = useRoute();

const form = reactive<API.UserLoginRequest>({
  userAccount: "",
  userPassword: "",
});

const disabled = computed(() =>  !(form.userAccount && form.userPassword));

/**
 * 提交
 */
const handleSubmit = async () => {
  if (disabled.value) {
    showFailToast("账号和密码不能为空");
    return;
  }
  showLoadingToast({ message: '登录中...', forbidClick: true});
  const res = await API.userController.userLogin(form);
  closeToast();
  if (res.data.code === 200) {
    showSuccessToast("登录成功");
    router.push({
      path: decodeURIComponent(route.query.redirect as string || "") || "/",
      replace: true,
    });
  } else {
    showFailToast("登录失败，" + res.data.message);
  }
};

/**
 * 微信登录
 */
const wxLogin = () => {
  let query = {};
  if (route.query.redirect) {
    query = {
      redirect: encodeURIComponent(route.query.redirect as string),
    };
  }
  router.push({
    path: "/auth/wx/login",
    query,
  })
};
</script>
